package mytomcat;

import mytomcat.config.ServletMappingConfig;
import mytomcat.core.MyRequest;
import mytomcat.core.MyResponse;
import mytomcat.mapping.ServletMapping;
import mytomcat.servlet.base.MyServlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <ul>
 * <li>Title:  MyTomcat</li>
 * <li>Description: TODO </li>
 * <li>Copyright: Copyright (c) 2018</li>
 *
 * </ul>
 *
 * @author swc
 * @version     V1.0
 * @date 2020/4/20 0020 上午 9:54
 */
public class MyTomcat {

    private  int port;

    private Map<String,String> urlServletMap = new HashMap<String, String>();


    public MyTomcat(int port) {
        this.port = port;
    }


    public void start(){
        initservletMapping();

        ServerSocket serverSocket =null;

        try {
            serverSocket = new ServerSocket(port);
            System.out.println(" myTomcat is start ...");

            while(true){
                Socket socket = serverSocket.accept();

                InputStream inputStream =socket.getInputStream();

                OutputStream outputStream =socket.getOutputStream();

                MyRequest myRequest =new MyRequest(inputStream,this.port);

                MyResponse myResponse =new MyResponse(outputStream);

                //请求连接为空  限制请求的url形式  进行拦截
                if(myRequest.getUrl()!=null && !"".equals(myRequest.getUrl())
                        && (myRequest.getUrl().contains(".html")
                        || myRequest.getUrl().contains(".jsp")
                        || myRequest.getUrl().contains(".ajax") )){
                    //请求分发
                    dispatch(myRequest,myResponse);
                }
                socket.close();
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private void dispatch(MyRequest myRequest, MyResponse myResponse) {
        String url =myRequest.getUrl();

        //去除请求地址的参数
        Pattern compile = Pattern.compile("[?](\\w|\\d)?");
        Matcher matcher = compile.matcher(url);

        if(matcher.find()){
            url = url.substring(0,url.indexOf(matcher.group()));
        }

        String clazz = urlServletMap.get(url);

        //反射
        try {
            //错误
            if(clazz==null || "".equals(clazz.trim())){
                clazz ="mytomcat.servlet.ErrorServlet";
            }
            Class aClass = Class.forName(clazz);

            Class<MyServlet> myServletClass = (Class<MyServlet>)aClass;
            MyServlet myServlet= myServletClass.newInstance();
            myServlet.service(myRequest,myResponse);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    private void initservletMapping() {
        for(ServletMapping servletMapping:ServletMappingConfig.servletMappingList){
            urlServletMap.put(servletMapping.getUrl(),servletMapping.getClazz());
        }
    }

    public static void main(String[] args) {
        new MyTomcat(8895).start();
    }
}
